<template>
  <div>
    <div class="header-fixed">
      <Header :text="text">
      <!-- 筛选条件 -->
      <section style="width: 100%">
          <div class="left">
            <div style="width: 80%">
              <el-input v-model="formLabelAlign.contractNo" :placeholder="`${$t('m.please')+$t('cImport.iContract')}`" size="mini">
                <el-button slot="append" icon="el-icon-search" @click="handleOk"></el-button>
              </el-input>
            </div>
          </div>
          <div class="right" @click="handleChoose">
            <span>{{$t('m.screen')}}<van-icon name="filter-o" /></span>
          </div>
      </section>
      </Header>
    </div>
    <!-- 右侧弹框 -->
    <van-popup v-model="show" position="right" @click-overlay="close" :style="{ width: '80%',height: '100%'}">
      <div class="top">
        <header>{{$t('m.screen')}}</header>
      </div>
      <div class="content">
        <div class="content-text">
          <el-form label-position="top" label-width="80px" :model="formLabelAlign" size="mini">
            <el-form-item :label="$t('cImport.iReceipt')">
              <el-button type="primary" round plain @click="handleStartDate($t('m.receivingDate'))">{{ dates.flightStartDate ? dates.flightStartDate.slice(0, 10) : 'Start'}}</el-button>
              <span style="padding: 0 2.778vw">~</span>
              <el-button type="warning" round plain @click="handleEndDate($t('m.receivingEnd'))">{{dates.flightEndDate ? dates.flightEndDate.slice(0, 10) : 'End'}}</el-button>
            </el-form-item>
            <el-form-item :label="$t('cImport.iArrival')">
              <el-button type="primary" round plain @click="handleStartDate($t('m.arrivalStart'))">{{dates.ArrivalStartDate ? dates.ArrivalStartDate.slice(0, 10) : 'Start'}}</el-button>
              <span style="padding: 0 2.778vw">~</span>
              <el-button type="warning" round plain @click="handleEndDate($t('m.arrivalEnd'))">{{dates.ArrivalEndDate ? dates.ArrivalEndDate.slice(0, 10) : 'End'}}</el-button>
            </el-form-item>
            <el-form-item :label="$t('cImport.iStorage')">
              <el-button type="primary" round plain @click="handleStartDate($t('m.warehousingStart'))">{{dates.StorageStartDate ? dates.StorageStartDate.slice(0, 10) : 'Start'}}</el-button>
              <span style="padding: 0 2.778vw">~</span>
              <el-button type="warning" round plain @click="handleEndDate($t('m.storageEnd'))">{{dates.StorageEndDate ? dates.StorageEndDate.slice(0, 10) : 'End'}}</el-button>
            </el-form-item>
            <el-form-item :label="$t('cImport.iOperation')">
              <el-select v-model="formLabelAlign.agentCode" :placeholder="$t('m.choose')">
                <el-option
                  v-for="(item,index) in agent"
                  :popper-append-to-body="false"
                  :key="index"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('cExport.transportState')">
              <el-button @click="handleSelectState">{{btnText}}</el-button>
            </el-form-item>
            <el-form-item :label="$t('cImport.iContract')">
              <el-input v-model="formLabelAlign.contractNo"></el-input>
            </el-form-item>
            <el-form-item :label="$t('cTransportSearch.partNum')">
              <el-input v-model="formLabelAlign.partNumber"></el-input>
            </el-form-item>
            <el-form-item :label="$t('cExport.mainWaybillNumber')">
              <el-input v-model="formLabelAlign.mainWaybillNumber"></el-input>
            </el-form-item>
            <el-form-item :label="$t('cExport.purchasingClerk')">
              <el-input v-model="formLabelAlign.purchasingClerk"></el-input>
            </el-form-item>
            <el-form-item :label="$t('cImport.iDeparture')">
              <el-input v-model="formLabelAlign.startShipmentHarbor"></el-input>
            </el-form-item>
            <el-form-item :label="$t('cExport.destinationHarbor')">
              <el-input v-model="formLabelAlign.destinationHarbor"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="bottom">
        <div>
          <el-button plain @click="close(1)">{{$t('btn.reset')}}</el-button>
          <el-button type="primary" @click="handleOk">{{$t('btn.ok')}}</el-button>
        </div>
      </div>
    </van-popup>
    <!-- 中心内容 -->
    <Scroll
        class="scroll-content"
        ref="scroll"
        @pulling="loadMore"
        @pullDown="handleDown"
    >
      <TransportDetail
          v-for="(item,index) in list"
          v-animation
          :index="index"
          :key="index"
          :class="item.aog === 'AOG' ? 'backColor':''"
          :transObj="item"
          @open="open(item)"
      >
      </TransportDetail>
      <div class="bottom-text" v-if="showBottom">-----{{$t('m.last')}}-----</div>
    </Scroll>
    <!-- 日期选择框 -->
    <div class="time" v-if="dateShow">
     <van-datetime-picker
        v-model="currentDate"
        type="date"
        :title="timeTitle"
        @confirm="confirm"
        @cancel="cancel"
      />
    </div>
    <!-- 状态选择框 -->
    <div class="time" v-if="stateShow">
      <van-picker
        :title="$t('cExport.transportState')"
        show-toolbar
        :columns="options"
        @confirm="handleState"
        @cancel="onCancel"
      />
    </div>
  </div>
</template>

<script>
import Header from '../../components/common/Header'
import TransportDetail from '../../components/common/import/TransportDetail'
import Scroll from "@/components/common/scroll/Scroll"
import { format, transportState } from "@/assets/js/common"
import { $import } from "@/api/import"

export default {
  components: {
    Header,
    TransportDetail,
    Scroll
  },
  data() {
    return {
      text: '',
      selected: '',
      options: [
        'state.all',
        'state.receivedFor',
        'state.shippedBut',
        'state.declared',
        'state.declaredBut',
        'state.releasedFor',
        'state.pickedUp',
        'state.warehousing',
        'state.completed'
      ],
      show: false,
      stateShow: false,
      formLabelAlign: {
        page: 0,
        limit: 10
      },
      dates: {
        flightStartDate: '',
        flightEndDate: '',
        ArrivalStartDate: '',
        ArrivalEndDate: '',
        StorageStartDate: '',
        StorageEndDate: ''
      },
      dateShow: false,
      timeTitle: '',
      currentDate: new Date(),
      agent: ['LMF','ABENH','BDEXH','NFHK','AA','AAA','KLE','LMEA'],
      list: [],
      isBottom: false,
      status: 0,
      btnText: 'state.all',
      showBottom: false,
      transportState,
      isRefresh: false // 记录刷新
    }
  },
  watch: {
    '$route' (val) {
      if (val.name === 'HomeWork') {
        this.isRefresh = true
        this.btnText = this.$t('state.all')
        this.formLabelAlign = this.$options.data().formLabelAlign
      }
    }
  },
  methods: {
    handleChoose() {
      this.show = !this.show
    },
    // 遮罩层关闭
    close(value) {
      if(value) {
        this.btnText = this.$t('state.all')
        this.formLabelAlign = this.$options.data().formLabelAlign
        this.dates = this.$options.data().dates
        this.handleDown()
      }
      this.dateShow = false
      this.stateShow = false
      this.show = false
    },
    // 选择开始时间
    handleStartDate(str) {
      this.timeTitle = str
      switch (this.timeTitle) {
        case `${this.$t('m.receivingDate')}`:
          this.dates.flightStartDate ? this.currentDate = new Date(this.dates.flightStartDate) : this.currentDate = new Date()
          break;
        case `${this.$t('m.arrivalStart')}`:
          this.dates.ArrivalStartDate ? this.currentDate = new Date(this.dates.ArrivalStartDate) : this.currentDate = new Date()
          break;
        case `${this.$t('m.warehousingStart')}`:
          this.dates.StorageStartDate ? this.currentDate = new Date(this.dates.StorageStartDate) : this.currentDate = new Date()
          break;
      }
      this.dateShow = true
    },
    // 选择结束时间
    handleEndDate(str) {
      this.timeTitle = str
      switch (this.timeTitle) {
        case `${this.$t('m.receivingEnd')}`:
          this.dates.flightEndDate ? this.currentDate = new Date(this.dates.flightEndDate) : this.currentDate = new Date()
          break;
        case `${this.$t('m.arrivalEnd')}`:
          this.dates.ArrivalEndDate ? this.currentDate = new Date(this.dates.ArrivalEndDate) : this.currentDate = new Date()
          break;
        case `${this.$t('m.storageEnd')}`:
          this.dates.StorageEndDate ? this.currentDate = new Date(this.dates.StorageEndDate) : this.currentDate = new Date()
          break;
      }
      this.dateShow = true
    },
    // 确定时间
    confirm() {
      switch (this.timeTitle) {
        case `${this.$t('m.receivingDate')}`:
          this.dates.flightStartDate = format(this.currentDate) + ' 00:00:00'
          break;
        case `${this.$t('m.arrivalStart')}`:
          this.dates.ArrivalStartDate = format(this.currentDate) + ' 23:59:59'
          break;
        case `${this.$t('m.warehousingStart')}`:
          this.dates.StorageStartDate = format(this.currentDate) + ' 00:00:00'
          break;
        case `${this.$t('m.receivingEnd')}`:
          this.dates.flightEndDate = format(this.currentDate) + ' 23:59:59'
          break;
        case `${this.$t('m.arrivalEnd')}`:
          this.dates.ArrivalEndDate = format(this.currentDate) + ' 00:00:00'
          break;
        case `${this.$t('m.storageEnd')}`:
          this.dates.StorageEndDate = format(this.currentDate) + ' 23:59:59'
          break;
      }
      this.dateShow = false
    },
    // 取消时间
    cancel() {
      this.dateShow = false
    },
    // 加载数据
    getList() {
      // if (this.list.length >= this.totalCount) return console.log('我也是有底线的')
      this.formLabelAlign.page = this.formLabelAlign.page + 1
      const obj = {
        ...this.formLabelAlign,
        ...this.dates
      }
      $import.getByStatus(obj)
             .then(res => {
               if (res.status === 200) {
                 const total = res.data.totalCount
                 this.list.push(...res.data.list)
                 total === this.list.length ? this.showBottom = true : this.showBottom = false
               }
               else {
                 this.$msg.fail(res.msg || res.message || '网络错误,请稍后再试!')
               }
             })
             .catch(err => this.$msg.fail(err.msg || err.message || '网络错误,请稍后再试!'))
             .finally(() => {
               this.$refs.scroll.refresh()
               this.$refs.scroll.finishPullUp()
             })
    },
    // 加载更过
    loadMore() {
      this.getList()
      this.$refs.scroll.refresh()
    },
    open(item) {
      const record = {
        mainWaybillNumber: item.mainWaybillNumber,
        cargoId: item.cargoId,
        transportId: item.transportId,
        wid: item.wid,
        contractNo: item.contractNoList[0].contractNo,
        waybillNumber: item.waybillNumber
      }

      // 为已经做过动画的标记 already 类
      const divs = document.querySelectorAll('.detail')
      for (let div of divs) {
        if ([...div.classList].indexOf('fadeInUp') !== -1) {
          div.classList.remove('fadeInUp')
          div.classList.add('already')
        }
      }
      console.log(divs)

      this.$router.push({
        path: '/import/importDetail',
        query: {
          type: `${this.$t('cExport.waybill')}: ` + item.mainWaybillNumber,
          record: JSON.stringify(record)
        }
      })
    },
    // 下拉刷新
    handleDown() {
      this.formLabelAlign.page = 1
      $import.getByStatus(this.formLabelAlign)
          .then(res => {
            if (res.status === 200) {
              this.list = []
              this.list.push(...res.data.list)
              this.$msg.success(this.$t('m.mRefresh'))
            }
            else {
              this.$msg.fail(res.msg || res.mesage || '网络错误,请稍后再试!')
            }
          })
          .catch(err => this.$msg.fail(err.msg || err.mesage || '网络错误,请稍后再试!'))
          .finally(() => {
            this.$refs.scroll.refresh()
            this.$refs.scroll.finishPullDownRefresh()
          })
    },
    handleSelectState() {
      this.stateShow = true
    },
    // 运输状态选择
    handleState(text) {
      if(text !== `${this.$t('state.all')}`) {
        this.transportState.forEach(item => {
          if(item.label == text) {
            this.formLabelAlign.status = item.value
          }
        })
      }
      else {
        delete this.formLabelAlign.status
      }
      this.btnText = text
      this.stateShow = false
    },
    // 取消
    onCancel() {
      this.stateShow = false
    },
    // 查询
    handleOk() {
      // this.formLabelAlign.startDate = this.changeTime()[0]
      // this.formLabelAlign.endDate = this.changeTime()[1]
      this.show = false
      this.list = []
      this.formLabelAlign.page = 0
      this.getList()
    }
  },
  created() {
    this.text = this.$t(this.$route.query.type)
    this.getList()
  },
  mounted() {
    this.options.map((item,index) => this.options[index] = this.$t(item))
    this.transportState.map((item,index) => this.transportState[index].label = this.$t(item.label))
    this.btnText = this.$t('state.all')
  },
  async activated() {
    this.text = this.$t(this.$route.query.type)
    // 从菜单导航栏进来重新刷新
    if (this.isRefresh) {
      this.formLabelAlign.page = 0
      this.list = []
      await this.getList()
      this.$refs.scroll.scroll.scrollTo(0, 0)
      this.isRefresh = false
    }
    else {
      this.$refs.scroll.refresh()
    }
  }
}
</script>

<style scoped>
.header-fixed {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
  width: 100%;
}
section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.389vw 0;
  background-color:#639df5;
  font-size: 4.167vw;
  font-weight: 580;
}
.left {
  flex: 6;
  display: flex;
  justify-content: center;
  color: white;
}
.left span {
  display: flex;
  width: 25%;
  justify-content: center;
  align-items: center;
}
select {
  width: 60%;
}
.right {
  flex: 1;
}
.right span {
  background-color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 16.056vw;
  border-radius: 1.389vw;
  font-weight: 500;
  padding: 2px 0;
  height: 28px;
}
.top header {
  height: 13.889vw;
  padding-left: 2.778vw;
  font-size: 5vw;
  line-height: 13.889vw;
  font-weight: 600;
  border-bottom: 0.278vw solid #797979;
}
.content {
  display: flex;
  justify-content: center;
}
.content-text {
  width: 90%;
  height: calc(100vh - 27.778vw);
  overflow-x:hidden;
  overflow-y:scroll;
}
/deep/.el-form-item__label {
  padding-bottom: 0px;
}
/deep/.el-form-item {
  margin: 0;
  padding: 2.778vw 0;
  border-bottom: 1px dashed black;
}
/deep/.el-form-item__label {
  font-size: 3.889vw;
}
.bottom {
  position: absolute;
  width: 100%;
  height: 13.889vw;
  bottom: 0;
  left: 0;
  background-color: white;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.time {
  width: 100%;
  position: fixed;
  z-index: 9999;
  bottom: 0;
  left: 0;
}
/deep/.el-checkbox-button span {
  margin: 1.389vw 0 0 1.389vw;
  border-left: 1px solid #DCDFE6;
  border-radius: 3px !important;
}
.bottom div {
  margin-right: 10px;
}
.backColor {
  background-color: rgba(255,165,0,.4) ;
}
/* better-scroll */
.scroll-content {
  position: absolute;
  top: 62px;
  left: 0;
  right: 0;
  height: calc(100vh - 72px);
  overflow: hidden;
}
/* 我也是有底线的 */
.bottom-text {
  display: flex;
  justify-content: center;
  align-items: center;
  color: rgba(0,0,0,.3);
}
/* 右侧弹框 */
/deep/.van-overlay {
  z-index: 1499 !important;
}
/deep/.van-popup {
  z-index: 1500 !important;
}
</style>
